//#include <dbus/dbus-glib.h>
#include <dbus/dbus.h>
#include <stdio.h>


int main(int argc, char *argv[]) {
    DBusError err; //这里用dbus自定义的函数处理error
    DBusConnection *conn;
    DBusMessage *msg; //封装signal的msg
        //signal 和 method 都抽象为msg
    DBusMessageIter arg; //和msg关联，由于指定signal参数
    dbus_uint32_t serial = 0; //记录消息发送序号
    const char *sigval = "Hello";
    int ret;
    dbus_error_init(&err);
    //1. get session conn
    conn = dbus_bus_get(DBUS_BUS_SESSION, &err);
    if(dbus_error_is_set(&err)) {
        fprintf(stderr, "Connection err: %s\n", err.message);
        dbus_error_free(&err); //释放err内部数据，并重新init
    }
    if(conn == NULL){
        return -1;
    }
#if 1
    //设置连接名(可选)
    ret = dbus_bus_request_name(
        conn, 
        "test.signal.source", 
        DBUS_NAME_FLAG_REPLACE_EXISTING,
        &err);
    if(dbus_error_is_set(&err)) {
        fprintf(stderr, "Requeset name error:%s\n", err.message);
        dbus_error_free(&err);
    }
    if(ret != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER)
        return -1;
#endif
    //2. create msg of signal
    if((msg = dbus_message_new_signal(
            "/test/signal/Object", //obj_path
            "test.signal.Type", //interface
            "Hello" /* singal name */ )) == NULL) { 
        fprintf(stderr, "Create singal msg failed!\n");       
        return -1;
    }
    //3. 置信号参数
    //关联arg
    dbus_message_iter_init_append(msg, &arg);
    if(!dbus_message_iter_append_basic(&arg, DBUS_TYPE_STRING, &sigval)) {
        fprintf(stderr, "Set singal arg faild!\n");
        return -1;
    }
    //4. 发送信号
    if(!dbus_connection_send(conn, msg, &serial)) { //这里
        fprintf(stderr, "Send signal failed!\n");
        return -1;
    }
    dbus_connection_flush(conn);
    printf("Send `Hello` siganl finished!\n");
       
}
